using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Web;

using Common;

namespace data
{
    public class securityLibs
    {
        public static int EffectiveUserType(data.userDataSet.tm_usersRow userRow, int loginPortalId)
        {
            // If assign portal is null , the user must be a system account to have NAD paermission
            if (userRow.IsportalIdNull())
            {
                if ( sysLibs.bitIsOn(userRow.userType, consts.constSYSBitPos)) return userRow.userType;
                return sysLibs.turnBitOff(userRow.userType, consts.constNADBitPos);
            }
            // NAD permission is only effective on assined portal
            if (userRow.portalId == loginPortalId) return userRow.userType;
            return sysLibs.turnBitOff(userRow.userType, consts.constNADBitPos);
        }
    }
    public class dataLibs
    {
        private static DateTime lastLogTime = DateTime.MinValue; //Last tiem where the log was added to database
        private static logDataSetTableAdapters.tm_click_counterTableAdapter clickCounterTA = new logDataSetTableAdapters.tm_click_counterTableAdapter();
        private static logDataSet.tm_click_counterDataTable clickCounterTbl = new logDataSet.tm_click_counterDataTable();
        private static logDataSet.tm_click_counterRow clickCounterRow;

        public static string lastErrorMessage = "";

     

        private static bool AddClickCounter(string type, int dnnTabId, string sourceAddress, int infoId, int userId)
        {
            try
            {
                clickCounterTbl.Clear();
                clickCounterRow = clickCounterTbl.Newtm_click_counterRow();
                clickCounterRow.onTime = DateTime.Now;
                clickCounterRow.type = type;
                clickCounterRow.tabId = dnnTabId;
                if (userId > 0) clickCounterRow.userId = userId;
                if (infoId > 0) clickCounterRow.infoId = infoId;
                clickCounterTbl.Addtm_click_counterRow(clickCounterRow);
                clickCounterTA.Update(clickCounterRow);
                return true;
            }
            catch (Exception exc)
            {
                lastErrorMessage = exc.ToString();
            }
            return false;
        }

        public static bool SaveClickCounter(string type, HttpRequest request)
        {
            int infoId = -1, userId = -1, dnnTabId=-1;
            dnnTabId = sysLibs.GetTabIdFromURL(request.Url.AbsoluteUri);
            if (dnnTabId < 0) return false;
            if (request.QueryString.Get("infoId") != null) 
                int.TryParse(request.QueryString["infoId"].ToString(),out infoId);
            if (request.QueryString.Get("userId") != null) return false;
                int.TryParse(request.QueryString["userId"].ToString(),out userId);
            return SaveClickCounter(type, dnnTabId, request.UserHostAddress, infoId, userId);
        }
        public static bool SaveClickCounter(HttpRequest request, string type, int infoId, int userId)
        {
            int dnnTabId = -1;
            //Log where the request come from 
            if (request.UrlReferrer != null)
                dnnTabId = sysLibs.GetTabIdFromURL(request.UrlReferrer.AbsoluteUri);
            if (dnnTabId == -1)
                dnnTabId = sysLibs.GetTabIdFromURL(request.Url.AbsoluteUri);
            if (dnnTabId == -1) return false;
            return SaveClickCounter(type, dnnTabId, request.UserHostAddress, infoId, userId);
        }
        public static bool SaveClickCounter(string type, int dnnTabId, string sourceAddress, int infoId, int userId)
        {   
            try
            {
               TimeSpan ts = DateTime.Now - lastLogTime;
               if (ts.TotalSeconds <=Common.systemSettings.sysIntervalTimeToCountClick) return true;
               if (AddClickCounter(type, dnnTabId,sourceAddress,infoId, userId))
                {
                    lastLogTime = DateTime.Now;
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                lastErrorMessage = ex.Message.ToString();
            }
            return false;
        }
        
        public static bool AddUserSyscode(int userId, ArrayList syscodeId)
        {

            lastErrorMessage = "";
            if (syscodeId.Count <= 0) return true;
            try
            {
                data.userDataSetTableAdapters.tm_user_syscodesTableAdapter tmUserSyscodeTA = new data.userDataSetTableAdapters.tm_user_syscodesTableAdapter();
                data.userDataSet.tm_user_syscodesDataTable tmUserSyscodeTbl = new data.userDataSet.tm_user_syscodesDataTable();
                data.userDataSet.tm_user_syscodesRow tmUserSyscodeRow;
                for (int i = 0; i < syscodeId.Count; i++)
                {
                    tmUserSyscodeRow = tmUserSyscodeTbl.Newtm_user_syscodesRow();
                    tmUserSyscodeRow.userId = userId;
                    tmUserSyscodeRow.syscodeId = int.Parse(syscodeId[i].ToString());
                    tmUserSyscodeTbl.Addtm_user_syscodesRow(tmUserSyscodeRow);
                    tmUserSyscodeTA.Update(tmUserSyscodeRow);
                }
                return true;
            }
            catch (Exception exc)
            {
                lastErrorMessage = exc.ToString();
            }
            return false;
        }
        public static bool GetInfoName(string type, int infoId, out string infoDesc)
        {
            infoDesc = null;
            try
            {
                if (infoId < 0) return false;
                switch (type)
                {
                    case Common.consts.constProfileProduct:
                        applicationDataSetTableAdapters.tm_productTA productTA = new applicationDataSetTableAdapters.tm_productTA();
                        productTA.Connection.ConnectionString = Common.sysLibs.GetConnectionString;
                        applicationDataSet.tm_productDataTable productTbl = new applicationDataSet.tm_productDataTable();
                        productTA.FillByProductId(productTbl, infoId);
                        if (productTbl.Rows.Count <= 0) return false;
                        infoDesc = ((applicationDataSet.tm_productRow)productTbl.Rows[0]).Name1;
                        return true;

                    case Common.consts.constProfileBuyRequest:
                        applicationDataSetTableAdapters.tm_buy_requestTA requestTA = new data.applicationDataSetTableAdapters.tm_buy_requestTA();
                        requestTA.Connection.ConnectionString = Common.sysLibs.GetConnectionString;
                        applicationDataSet.tm_buy_requestDataTable requestTbl = new applicationDataSet.tm_buy_requestDataTable();
                        requestTA.FillByRequestId(requestTbl, infoId);
                        if (requestTbl.Rows.Count <= 0) return false;
                        infoDesc = ((applicationDataSet.tm_buy_requestRow)requestTbl.Rows[0]).Name1;
                        return true;

                    case Common.consts.constProfileEnterprise:
                        userDataSetTableAdapters.tm_usersTableAdapter userTA;
                        userTA = new userDataSetTableAdapters.tm_usersTableAdapter();
                        userTA.ClearBeforeFill = true;

                        userTA.Connection.ConnectionString = Common.sysLibs.GetConnectionString;
                        userDataSet.tm_usersDataTable userTbl = new userDataSet.tm_usersDataTable();
                        userTA.FillByUserId(userTbl, infoId);
                        if (userTbl.Rows.Count <= 0) return false;
                        int userType = ((userDataSet.tm_usersRow)userTbl.Rows[0]).userType;
                        if (Common.sysLibs.bitIsOn(userType, Common.consts.constENTBitPos))
                            infoDesc = ((userDataSet.tm_usersRow)userTbl.Rows[0]).companyName1;
                        else infoDesc = ((userDataSet.tm_usersRow)userTbl.Rows[0]).fullName;
                        return true;
                }
            }
            catch { }
            return false;
        }
    }
}
